package com.business.user.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.business.common.constant.MessageConstant;
import com.business.common.enums.BusinessExceptionEnum;
import com.business.common.enums.ErrorEnum;
import com.business.common.exception.BusinessException;
import com.business.common.exception.CustomException;
import com.business.common.utils.PageUtils;
import com.business.common.utils.StrKit;
import com.business.user.dto.UserParams;
import com.business.user.entity.Message;
import com.business.user.entity.UserConcern;
import com.business.user.entity.UserDetails;
import com.business.user.entity.vo.UserVo;
import com.business.user.mapper.UserConcernMapper;
import com.business.user.mapper.UserDetailsMapper;
import com.business.user.rabbitMq.RabbitMqSender;
import com.business.user.service.UserConcernService;
import com.business.user.service.UserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;


/**
 * 关注表:业务接口实现类
 *
 * @author chenjiehong
 * @date 2019-11-29 14:28:27
 * @since 1.0
 */
@Service
public class UserConcernServiceImpl implements UserConcernService {

    @Autowired
    private UserConcernMapper userConcernMapper;

    @Autowired
    private UserDetailsMapper userDetailsMapper;

    @Autowired
    private RabbitMqSender rabbitMqSender;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    @Transactional
    public UserConcern add(UserConcern userConcern) {
        if (userConcern.getUserId() == null) {
            throw new CustomException(ErrorEnum.PARAMS_LOSE, "userId");
        }
        if (userConcern.getConcernUserId() == null) {
            throw new CustomException(ErrorEnum.PARAMS_LOSE, "concernUserId");
        }
        if (userConcern.getUserId() == userConcern.getConcernUserId()) {
            throw new BusinessException(BusinessExceptionEnum.USER_CONCERN_ERROR);
        }
        Integer count = userConcernMapper.selectCount(new EntityWrapper<UserConcern>().eq("user_id", userConcern.getUserId()).eq("concern_user_id", userConcern.getConcernUserId()));
        if (count > 0) {
            throw new BusinessException(BusinessExceptionEnum.USER_CONCERN_EXIST);
        }
        //判断是否超过限制关注人数  普通用户 200 人 会员 2000
        Integer concernCount = userConcernMapper.selectCount(new EntityWrapper<UserConcern>().eq("user_id", userConcern.getUserId()));
        Integer userType = userDetailsMapper.getType(userConcern.getUserId());
        if (userType == 0 && concernCount >= 200) {
            throw new BusinessException(BusinessExceptionEnum.USER_CONCERN_UPPER_LIMIT);
        } else if (userType == 1 && concernCount >= 2000) {
            throw new BusinessException(BusinessExceptionEnum.MEMBER_CONCERN_UPPER_LIMIT);
        }
        //判断是否互相关注
        UserConcern params = new UserConcern();
        params.setUserId(userConcern.getConcernUserId());
        params.setConcernUserId(userConcern.getUserId());
        params = userConcernMapper.selectOne(params);
        //是互相关注
        if (params != null) {
            params.setIsEachOther(1);
            userConcern.setIsEachOther(1);
            userConcernMapper.updateById(params);
        }
        userConcern.setCreateTime(new Date());
        Integer result = userConcernMapper.insert(userConcern);
        if (result > 0) {
            //关注数量
            rabbitMqSender.sendAddUserDataQuantity(userConcern.getUserId(), "friend", 1);
            //粉丝数量
            rabbitMqSender.sendAddUserDataQuantity(userConcern.getConcernUserId(), "fans", 1);

            //发送粉丝增加消息
            Message message = new Message();
            message.setUserId(userConcern.getConcernUserId());
            message.setFromUserId(userConcern.getUserId());
            message.setType(2);
            message.setContent(MessageConstant.USER_CONCERN_ADD);
            rabbitMqSender.addMessage(message);
        }

        return userConcern;
    }

    @Override
    @Transactional
    public Integer delete(UserConcern userConcern) {
        if (userConcern.getUserId() == null) {
            throw new CustomException(ErrorEnum.PARAMS_LOSE, "userId");
        }
        if (userConcern.getConcernUserId() == null) {
            throw new CustomException(ErrorEnum.PARAMS_LOSE, "concernUserId");
        }
        //判断是否互相关注
        UserConcern params = new UserConcern();
        params.setUserId(userConcern.getConcernUserId());
        params.setConcernUserId(userConcern.getUserId());
        params = userConcernMapper.selectOne(params);
        //是互相关注
        if (params != null) {
            params.setIsEachOther(0);
            userConcernMapper.updateById(params);
        }
        Integer result = userConcernMapper.delete(new EntityWrapper<UserConcern>().eq("user_id", userConcern.getUserId()).eq("concern_user_id", userConcern.getConcernUserId()));
        if (result > 0) {
            //关注数量
            rabbitMqSender.sendAddUserDataQuantity(userConcern.getUserId(), "friend", -1);
            //粉丝数量
            rabbitMqSender.sendAddUserDataQuantity(userConcern.getConcernUserId(), "fans", -1);
            return result;
        } else {
            throw new CustomException(ErrorEnum.UNKNOWN_ERROR);
        }


    }

    @Override
    @Transactional
    public Integer deleteList(Integer userId, List<Integer> userConcernIdList) {
        List<Integer> resultList = new ArrayList<>(userConcernIdList.size());
        userConcernIdList.forEach(userConcernId -> {
            UserConcern userConcern = new UserConcern();
            userConcern.setUserId(userId);
            userConcern.setConcernUserId(userConcernId);
            Integer r = this.delete(userConcern);
            resultList.add(userConcernId);
        });
        return 1;
    }

    /**
     * 封装条件
     *
     * @param userParams
     * @return
     */
    private void setWrapper(EntityWrapper entityWrapper, UserParams userParams) {
        //状态
        entityWrapper.eq("u.state", 1);
        if (StrKit.isNotEmpty(userParams.getProvinceCode())) {
            entityWrapper.eq("u.province_code", userParams.getProvinceCode());
        }
        if (StrKit.isNotEmpty(userParams.getCityCode())) {
            entityWrapper.eq("u.city_code", userParams.getCityCode());
        }
        if (userParams.getType() != null) {
            entityWrapper.eq("u.type", userParams.getType());
        }
        if (userParams.getCreditLevel() != null) {
            entityWrapper.eq("u.credit_level", userParams.getCreditLevel());
        }
        //行业
        if (StrKit.isNotEmpty(userParams.getParentCategoryCode())) {
            entityWrapper.eq(" u.parent_category_code ", userParams.getParentCategoryCode());
        }
        if (StrKit.isNotEmpty(userParams.getSubCategoryCode())) {
            entityWrapper.eq(" u.sub_category_code ", userParams.getSubCategoryCode());
        }
        //职位
        if (StrKit.isNotEmpty(userParams.getPosition())) {
            entityWrapper.like("u.position", userParams.getPosition());
        }
        //公司
        if (StrKit.isNotEmpty(userParams.getCompany())) {
            entityWrapper.like("u.company", userParams.getCompany());
        }
        //名称
        if (StrKit.isNotEmpty(userParams.getName())) {
            entityWrapper.like("u.real_name", userParams.getName());
        }
        //模糊搜索
        if (StrKit.isNotEmpty(userParams.getLikeStr())) {
            entityWrapper.and(" ( u.real_name like {0} or u.company like {0} or u.tags like {0} or u.profession like {0} ) ", "%" + userParams.getLikeStr() + "%");
        }
        //排序
        if (StrKit.isNotEmpty(userParams.getSortField())) {
            boolean sortType;
            if (userParams.getSortType() == null || userParams.getSortType() == 1) {
                sortType = false;
            } else {
                sortType = true;
            }
            String sortField = "";
            if (userParams.getSortField().equals("friend")) {
                sortField = "friend_quantity";
            } else if (userParams.getSortField().equals("dynamic")) {
                sortField = "dynamic_quantity";
            }
            if (userParams.getSortField().equals("fans")) {
                sortField = "fans_quantity";
            }
            entityWrapper.orderBy("ud." + sortField, sortType);
        } else {
            //默认排序信息完成度 和创建时间 倒序
            entityWrapper.orderBy("u.create_time,u.degree", false);
        }
    }

    @Override
    public PageUtils queryFriendPage(Page<UserDetails> page, Integer userId, UserParams userParams) {
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("uc.user_id", userId);
        setWrapper(entityWrapper, userParams);
        page.setOptimizeCount(true);
        List<UserVo> users = userDetailsMapper.queryFriendPage(page, entityWrapper);
        PageUtils pageUtils = new PageUtils(users, page.getTotal());
        return pageUtils;
    }

    @Override
    public Set<Integer> queryFriendList(Integer userId) {
        Set<Integer> userIds = userConcernMapper.queryFriendList(userId);
        return userIds;
    }


    @Override
    public PageUtils queryFansPage(Page<UserDetails> page, Integer userId, UserParams userParams) {
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("uc.concern_user_id", userId);
        setWrapper(entityWrapper, userParams);
        page.setOptimizeCount(true);
        List<UserVo> users = userDetailsMapper.queryFansPage(page, entityWrapper);
        PageUtils pageUtils = new PageUtils(users, page.getTotal());
        return pageUtils;
    }

    @Override
    public PageUtils queryUserPage(Page<UserDetails> page, Integer userId, UserParams userParams) {
        EntityWrapper entityWrapper = new EntityWrapper();
        setWrapper(entityWrapper, userParams);
        if (userId != null) {
            entityWrapper.ne("u.user_id", userId);
        }
        page.setOptimizeCount(true);
        List<UserVo> users = userDetailsMapper.queryPage(page, entityWrapper, userId);
        PageUtils pageUtils = new PageUtils(users, page.getTotal());
        return pageUtils;
    }

    @Override
    public PageUtils queryRecommendUserPage(Page<UserDetails> page, Integer userId) {
        EntityWrapper entityWrapper = new EntityWrapper();
        //会员才会推荐
        entityWrapper.eq("u.type", 1).orderBy("u.create_time,u.degree", false);
        if (userId != null) {
            UserDetails userDetails = userDetailsService.query(userId);
            entityWrapper.ne("u.user_id", userId).and(" ( sub_category_code = {0} or parent_category_code = {1} ) ", userDetails.getSubCategoryCode(), userDetails.getParentCategoryCode());
        }
        page.setOptimizeCount(true);
        List<UserVo> users = userDetailsMapper.queryRecommendUserPage(page, entityWrapper, userId);
        PageUtils pageUtils = new PageUtils(users, page.getTotal());
        return pageUtils;
    }


}